package com.jay.media.music.ui.file

import android.os.Environment
import android.view.View
import androidx.appcompat.widget.PopupMenu
import androidx.appcompat.widget.Toolbar
import com.jay.base.ui.BaseFragment
import com.jay.codec.soft.CodecUtils
import com.jay.media.kit.LogHelper
import com.jay.media.music.ui.HomeActivity
import com.jay.media.music.ui.R
import java.io.File

/**
 * @author xuzhou4
 * @date 2021/12/22
 */
class FileFragment : BaseFragment(), OnFileItemClickListener {

    private lateinit var mToolbar: Toolbar
    override fun layoutId(): Int = R.layout.fragment_file

    override fun initView(view: View) {
        mToolbar = requireView().findViewById(R.id.toolbar)
        (mActivity as HomeActivity).setupToolbarNavBar(mToolbar)
        naviTo(Environment.getExternalStorageDirectory().absolutePath)
    }

    private fun naviTo(path: String) {
        val transaction = childFragmentManager.beginTransaction()
        val fileBrowserFragment = FileBrowserFragment.newInstance(path)
        fileBrowserFragment.setOnFileItemClickListener(this)
        transaction.replace(R.id.file_container, fileBrowserFragment)
        transaction.addToBackStack(path)
        transaction.commit()
    }

    override fun onItemClick(file: File, view: View) {
        LogHelper.d(TAG, "onItemClick() called with: file = $file")
        if (file.isDirectory) {
            naviTo(file.absolutePath)
        } else {

        }
    }

    override fun onItemMenuClick(file: File, view: View) {
        val popupMenu = PopupMenu(mActivity, view)
        popupMenu.menuInflater.inflate(R.menu.menu_file, popupMenu.menu)
        popupMenu.setOnMenuItemClickListener {
            when (it.itemId) {
                R.id.action_detail -> {
                }
                R.id.action_trans -> {
                    CodecUtils.parseMP3(file.absolutePath)
                }
                else -> {
                }
            }
            true
        }
        popupMenu.show()
    }
}